package com.tc.juc.design;

import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: tianchao
 * @Date: 2021/10/4 19:14
 * @Description:
 */
@Slf4j
public class TestJiaoTiAWaitSignal {

    public static void main(String[] args) {
        AWaitSignal waitNotify = new AWaitSignal(10);
        Condition a = waitNotify.newCondition();
        Condition b = waitNotify.newCondition();
        Condition c = waitNotify.newCondition();
        Thread t1 = new Thread(()->{waitNotify.print("a", a, b);},"t1");
        Thread t2 = new Thread(()->{waitNotify.print("b", b, c);},"t2");
        Thread t3 = new Thread(()->{waitNotify.print("c", c, a);},"t3");
        t1.start();
        t2.start();
        t3.start();
        log.info("获取锁");
        waitNotify.lock();
        log.info("唤醒a");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        a.signalAll();
        waitNotify.unlock();

    }
}
class  AWaitSignal extends ReentrantLock{
    int loopNum = 5;

    public AWaitSignal(int loopNum) {
        this.loopNum = loopNum;
    }

    public void print(String str, Condition current,Condition next){
        for (int i=0;i<loopNum;i++){
            lock();
            try {
                try {
                    current.await();
                    System.out.print(str);
                    next.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }finally {
                unlock();
            }
        }
    }
}
